package com.stationbuilding.fragment.safe;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.stationbuilding.MyApplication;
import com.stationbuilding.R;
import com.stationbuilding.adapter.SelectListAdapter;
import com.stationbuilding.api.RetrofitManager;
import com.stationbuilding.bean.DictBean;
import com.stationbuilding.bean.DictListBean;
import com.stationbuilding.bean.SubdivisionBean;
import com.stationbuilding.bean.SubdivisionListBean;
import com.stationbuilding.bean.QuestionTypeBean;
import com.stationbuilding.bean.QuestionTypeListBean;
import com.stationbuilding.bean.UserBean;
import com.stationbuilding.bean.UserListBean;
import com.stationbuilding.constants.Constants;
import com.stationbuilding.utils.PreferenceHelper;
import com.zhy.tree.bean.Node;
import com.zhy.tree.bean.TreeListViewAdapter;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class SafeSelectFragment extends Fragment {

    private View view;
    private SelectListAdapter listViewAdapter;
    private ProgressDialog dialog;//加载提示
    private LinearLayout emptyView;//空试图
    private List<DictBean> dictList = new ArrayList<>();
    private List<UserBean> userList = new ArrayList<>();
    private List<SubdivisionBean> treeList = new ArrayList<>();
    private List<QuestionTypeBean> questionTypeList = new ArrayList<>();
    private int selectPosition;
    private int id;
    private ListView listView;
    private String token = PreferenceHelper.getInstance(getActivity()).getToken();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_tree_select, container, false);
        id = getArguments().getInt("id");
        init();
        return view;
    }

    /**
     * 初始化操作
     */
    private void init() {
        emptyView = (LinearLayout) view.findViewById(R.id.empty_view);
        listView = (ListView) view.findViewById(R.id.list);

        RetrofitManager.getInstance().setOnInternetListener(new RetrofitManager.OnInternetListener() {
            @Override
            public void internetListener() {
                emptyView.setVisibility(View.VISIBLE);
            }
        });
        if (id == R.id.question_type) {
            Node node = new Node();
            node.setId("0");
            loadQuestionTypeList(node, 0);
        } else if (id == R.id.question_level) {
            loadLevelList();
        } else if (id == R.id.subdivision) {
            Node node = new Node();
            node.setId("0");
            loadModelList(node, 0);
        } else if (id == R.id.liable_person) {
//            loadUserList(Constants.ROLE_ID_PERSON_LIABLE);
        } else if (id == R.id.supervisor) {
//            loadUserList(Constants.ROLE_ID_SUPERVISOR);
        } else if (id == R.id.acceptor) {
//            loadUserList(Constants.ROLE_ID_ACCEPTOR);
        }
    }

    /**
     * 设置选择结果
     */
    private void setResult(Node node, boolean parentFlag) {
        Intent intent = new Intent();
        intent.putExtra("id", node.getId());
        intent.putExtra("name", node.getName());
        if (parentFlag) {
            setParentIdAndName(node, intent);
            setOtherProperty(node, intent);
        }
        getActivity().setResult(Activity.RESULT_OK, intent);
        getActivity().finish();
    }

    /**
     * 设置选择结果的父节点
     */
    private void setParentIdAndName (Node node, Intent intent) {
        Node parentNode = node.getParent();
        if (parentNode != null) {
            String id = intent.getStringExtra("id");
            String name = intent.getStringExtra("name");
            id = parentNode.getId() + Constants.COMMA + id;
            name = parentNode.getName() + Constants.ARROW_RIGHT + name;
            intent.putExtra("id", id);
            intent.putExtra("name", name);
            setParentIdAndName(parentNode, intent);
        }
    }

    /**
     * 设置其他属性
     */
    private void setOtherProperty (Node node, Intent intent) {
        for (QuestionTypeBean questionTypeBean : questionTypeList) {
            if (questionTypeBean.getId().equals(node.getId())) {
                intent.putExtra("measures", questionTypeBean.getMeasures());
                intent.putExtra("score", questionTypeBean.getScore());
                intent.putExtra("minScore", questionTypeBean.getMinScore());
                intent.putExtra("maxScore", questionTypeBean.getMaxScore());
                break;
            }
        }
    }

    /**
     * 问题类型数据加载
     */
    private void loadQuestionTypeList(final Node node, final int level) {
        final int firstVisiblePosition = listView.getFirstVisiblePosition();
        RetrofitManager.toSubscribe(
                RetrofitManager.getApiService().getQuestionTypeListByPid(token, node.getId(), Constants.QUESTION_TYPE_SAFE),
                new Observer<QuestionTypeListBean>() {

            @Override
            public void onComplete() {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                listView.setSelectionFromTop(firstVisiblePosition, 0);
            }

            @Override
            public void onError(Throwable e) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                Toast.makeText(getActivity(), "数据加载出错，请稍后再试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSubscribe(@NonNull Disposable d) {
                dialog = ProgressDialog.show(getActivity(), null, "加载数据...");
            }

            @Override
            public void onNext(QuestionTypeListBean questionTypeListBean) {
                questionTypeList.addAll(questionTypeListBean.getQuestionTypeList());
                emptyView.setVisibility(View.GONE);
                try {
                    listViewAdapter = new SelectListAdapter<>(listView, MyApplication.getContext(), questionTypeList, level, node);
                    listViewAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {
                        @Override
                        public void onClick(Node node, int position) {
                            selectPosition = position;
                            if (node.isLeaf()) {
                                setResult(node, true);
                            } else {
                                if (node.isExpand()) {
                                    for (int i = 0; i < questionTypeList.size(); i++) {
                                        if (questionTypeList.get(i).getLevel() > node.getLevel()) {
                                            questionTypeList.remove(i);
                                            i--;
                                        }
                                    }
                                    loadQuestionTypeList(node, node.getLevel() + 1);
                                }
                            }
                        }
                    });
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                listView.setAdapter(listViewAdapter);
            }
        });
    }

    /**
     * 问题等级数据加载
     */
    private void loadLevelList() {
        RetrofitManager.toSubscribe(
                RetrofitManager.getApiService().getDictListByPid(token, Constants.DICT_ID_QUESTION_LEVEL),
                new Observer<DictListBean>() {

            @Override
            public void onComplete() {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable e) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                Toast.makeText(getActivity(), "数据加载出错，请稍后再试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSubscribe(@NonNull Disposable d) {
                dialog = ProgressDialog.show(getActivity(), null, "加载数据...");
            }

            @Override
            public void onNext(DictListBean dictListBean) {
                dictList = dictListBean.getDictList();
                emptyView.setVisibility(View.GONE);
                try {
                    listViewAdapter = new SelectListAdapter<>(listView, MyApplication.getContext(), dictList, 0, null);
                    listViewAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {
                        @Override
                        public void onClick(Node node, int position) {
                            if (node.isLeaf()) {
                                setResult(node, false);
                            }
                        }
                    });
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                listView.setAdapter(listViewAdapter);
            }
        });
    }

    /**
     * 模型数据加载
     */
    private void loadModelList(final Node node, final int level) {
        RetrofitManager.toSubscribe(RetrofitManager.getApiService().getSubdivisionList(token), new Observer<SubdivisionListBean>() {

            @Override
            public void onComplete() {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                listView.post(new Runnable() {
                    @Override
                    public void run() {
                        listView.setSelection(selectPosition);
                    }
                });
            }

            @Override
            public void onError(Throwable e) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                Toast.makeText(getActivity(), "数据加载出错，请稍后再试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSubscribe(@NonNull Disposable d) {
                dialog = ProgressDialog.show(getActivity(), null, "加载数据...");
            }

            @Override
            public void onNext(SubdivisionListBean subdivisionListBean) {
                List<SubdivisionBean> list = subdivisionListBean.getFlowSectionEntities();
                treeList.addAll(list);
                emptyView.setVisibility(View.GONE);
                try {
                    listViewAdapter = new SelectListAdapter<>(listView, MyApplication.getContext(), treeList, level, node);
                    listViewAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {
                        @Override
                        public void onClick(Node node, int position) {
                            selectPosition = position;
                            if (node.isLeaf()) {
                                setResult(node, false);
                            } else {
                                if (node.isExpand()) {
                                    for (int i = 0; i < treeList.size(); i++) {
                                        if (treeList.get(i).getLv() > node.getLevel()) {
                                            treeList.remove(i);
                                            i--;
                                        }
                                    }
                                    loadModelList(node, node.getLevel() + 1);
                                }
                            }
                        }
                    });
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                listView.setAdapter(listViewAdapter);
            }
        });
    }
//
//    /**
//     * 责任人数据加载
//     */
//    private void loadUserList(int roleId) {
//        RetrofitManager.toSubscribe(
//                RetrofitManager.getApiService().getUserListByRoleId(token, roleId),
//                new Observer<UserListBean>() {
//
//            @Override
//            public void onComplete() {
//                if (dialog.isShowing()) {
//                    dialog.dismiss();
//                }
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                if (dialog.isShowing()) {
//                    dialog.dismiss();
//                }
//                Toast.makeText(getActivity(), "数据加载出错，请稍后再试", Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onSubscribe(@NonNull Disposable d) {
//                dialog = ProgressDialog.show(getActivity(), null, "加载数据...");
//            }
//
//            @Override
//            public void onNext(UserListBean userListBean) {
//                userList = userListBean.getUserList();
//                emptyView.setVisibility(View.GONE);
//                try {
//                    listViewAdapter = new SelectListAdapter<>(listView, MyApplication.getContext(), userList, 0, null);
//                    listViewAdapter.setOnTreeNodeClickListener(new TreeListViewAdapter.OnTreeNodeClickListener() {
//                        @Override
//                        public void onClick(Node node, int position) {
//                            if (node.isLeaf()) {
//                                setResult(node, false);
//                            }
//                        }
//                    });
//                } catch (IllegalAccessException e) {
//                    e.printStackTrace();
//                }
//                listView.setAdapter(listViewAdapter);
//            }
//        });
//    }
}
